import re

from flask import render_template, request, redirect, url_for, flash
from flask_login import login_user, logout_user

from apps.models.base import db
from apps.forms.auth import RegisterForm, LoginForm
from apps.models.user import User
from apps.utils.mail import send_mail
from . import web


@web.route('/register/', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User()
        user.set_attr(form.data)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('web.login'))
    return render_template('auth/register.html', form=form)


@web.route('/login', methods=['GET', 'POST'])
def login():
    form = {'data': ''}
    if request.method == 'POST':
        form = LoginForm(request.form)
        if form.validate():
            user = User.query.filter_by(email=form.email.data).first()
            if user and user.check_password(form.password.data):
                login_user(user, remember=True)
                next = request.args.get('next')
                if not next or not next.startswith('/'):
                    next = url_for('web.index')
                return redirect(next)
            else:
                flash('用户不存在或密码错误！')
    return render_template('auth/login.html', form=form)


@web.route('/reset/password', methods=['GET', 'POST'])
def forget_password_request():
    if request.method == 'POST':
        email = request.form.get('email').strip()
        is_valid = bool(re.search(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', email))
        if not is_valid:
            flash('请输入正确格式的邮箱！')
        else:
            user = User.query.filter_by(email=email).first_or_404()
            send_mail(email, subject='【鱼书】找回密码', template='email/reset_password.html', user=user, token=user.gene_token())
            flash('邮件发送成功，请注意查收！')
    return render_template('auth/forget_password_request.html')


@web.route('/reset/password/<token>', methods=['GET', 'POST'])
def forget_password(token):
    if request.method == 'POST':
        new_pwd = request.form.get('password1')
        confirm = request.form.get('password2')
        if new_pwd == confirm and len(new_pwd) > 5:
            status = User.reset_pwd(token, new_pwd)
            if status:
                flash('密码重置成功，请使用新密码登录。')
                return redirect(url_for('web.login'))
            flash('密码更新失败！')
        else:
            flash('两次密码不一致或密码少于6位！')
    return render_template('auth/forget_password.html')


@web.route('/change/password', methods=['GET', 'POST'])
def change_password():
    pass


@web.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('web.login'))
